import React from "react"
import store from '@/store'

export function withUser(InnerComponent) {
    return function OuterComponent(props) {
        let userInfo = localStorage.getItem('userInfo')
        try {
            userInfo = JSON.parse(userInfo) || {}
        } catch (err) {
            userInfo = {}
        }
        return <InnerComponent userInfo={userInfo} {...props}></InnerComponent>
    }
}

// 共享redux所有属性
export function withRedux(InnerComponent) {

    class OuterComponent extends React.Component {
        state = {
            reduxData: {}
        }
        componentDidMount() {
            let state = store.getState();
            this.setState({
                reduxData: state
            })
            store.subscribe(() => {
                state = store.getState()
                this.setState({
                    reduxData: state
                })
            })
        }
        render() {
            return <InnerComponent {...this.props} {...this.state.reduxData} dispatch={store.dispatch}></InnerComponent>
        }
    }

    return OuterComponent
}

// withRedux(App)
export function withStore(mapStateToProps, mapDispatchToProps) {
    return function hoc(InnerComponent) {
        return class OuterComponent extends React.Component {
            state = {
                data: {},
                methods: {}
            }
            getData() {
                const state = store.getState()
                if(typeof mapStateToProps === 'function'){
                    let data = mapStateToProps(state) || {}
                    this.setState({
                        data,
                    })
                }

                // methods必须包含一个默认的dispatch
                let methods = { dispatch: store.dispatch }
                if(typeof mapDispatchToProps === 'function'){
                    methods = mapDispatchToProps(store.dispatch)
                    
                }

                this.setState({
                    methods
                })
            }
            componentDidMount() {
                this.getData()

                // redux数据更新时
                store.subscribe(() => {
                    this.getData()
                })
            }
            render() {
                const { data, methods } = this.state;
                return <InnerComponent {...data} {...methods} {...this.props}></InnerComponent>
            }
        }
    }
}
